package com.contacts.controller;

import com.contacts.context.BaseContext;
import com.contacts.pojo.User;
import com.contacts.result.PageResult;
import com.contacts.result.Result;
import com.contacts.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin(origins = "*")
@RestController
@Slf4j
@Api(tags = "用户接口")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 添加新用户
     * @param user
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/user/enrollment")
    public Result addUser(@RequestBody User user) {
        userService.addUser(user);
        return Result.success("添加用户成功");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @ApiOperation("退出登录")
    @PostMapping("/user/logout")
    public Result logout(HttpServletRequest request) {
        //清理session中保存的当前用户id
        request.getSession().removeAttribute("id");
        //删掉在线程中存储的id
        BaseContext.removeCurrentId();
        return Result.success("退出成功");
    }

    /**
     * 带条件的分页查询
     * @param category
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation("带条件的分页查询")
    @GetMapping("/user/page")
    public Result page(String category, String name, Integer page, Integer pageSize) {
        //从线程中获得userId
        Integer userId = BaseContext.getCurrentId();
        //记录日志
        log.info("分页查询参数：{},{},{},{}", page, pageSize,name,category);
        //调用业务层进行查询
        PageResult pageResult = userService.page(category, name, page, pageSize, userId);
        //响应
        return Result.success(pageResult);
    }
}
